<template>
  <div>
    <!-- 查询表单 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="KEY">
          <el-input
            style="width: 350px"
            v-model.trim="searchModel.generalType"
            placeholder="请输入KEY"
          />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker
            v-model="searchModel.createDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" color="#ea5b24" @click="search()"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            color="#ea5b24"
            @click="showDialog(0, null)"
            v-if="pinia.isShow[98]"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column prop="generalType" label="KEY" />
        <el-table-column prop="generalContent" label="内容" />
        <!-- <el-table-column prop="editor" width="120" label="最后修改人ID" /> -->
        <el-table-column prop="editorName" width="180" label="最后修改人姓名" />
        <el-table-column prop="remake" label="备注" />
        <el-table-column prop="gmtEdit" width="160" label="更新时间" />
        <el-table-column fixed="right" width="80" label="操作">
          <template v-slot:default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="showDialog(1, scope.row)"
              v-if="pinia.isShow[99]"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>

    <!--添加/编辑管理员表单 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      center="true"
      modal="true"
      width="30%"
    >
      <el-form :model="configModel" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="KEY："
          :label-width="editFormLabelWidth"
          prop="generalType"
        >
          <el-input
            v-model.trim="configModel.generalType"
            autocomplete="off"
            v-if="dialogType === 0"
          />
          <span v-else>{{ configModel.generalType }}</span>
        </el-form-item>
        <el-form-item
          label="内容："
          :label-width="editFormLabelWidth"
          prop="generalContent"
        >
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 10 }"
            v-model.trim="configModel.generalContent"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="备注："
          :label-width="editFormLabelWidth"
          prop="remake"
        >
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 10 }"
            v-model.trim="configModel.remake"
            autocomplete="off"
            v-if="dialogType === 0"
          />
          <span v-else>{{ configModel.remake }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="formSubmit(ruleFormRef)"
            color="#ea5b24"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import {
  findUniversalConfigApi,
  addUniversalConfigApi,
  editUniversalConfigApi,
} from "../../../api/index";
import { formatDateTime } from "../../../utils/formatDateTime";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 控制对话框
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogType = ref(0);
const editFormLabelWidth = "80px";
// 搜索模型
const searchModel: any = reactive({
  generalType: null,
  createDate: null,
  startTime: null,
  endTime: null,
  page: page,
  size: size,
});
// 添加/编辑模型
const configModel = reactive({
  id: null,
  generalType: null,
  generalContent: null,
  remake: null,
});

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  generalType: [{ required: true, message: "请输入KEY", trigger: "blur" }],
});

// 翻页
let flipData = reactive({
  page: page,
  size: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.page = page.value;
  searchConfig(flipData);
};

// 控制添加/编辑dialog显示
const showDialog = (type: number, row) => {
  dialogVisible.value = true;
  dialogType.value = type;
  ruleFormRef.value ? ruleFormRef.value.clearValidate() : false;
  if (type === 0) {
    //添加管理员
    dialogTitle.value = "添加配置";
    Object.keys(configModel).forEach((key) => (configModel[key] = ""));
  } else {
    //编辑管理员
    dialogTitle.value = "编辑配置";
    configModel.id = row.id;
    configModel.generalType = row.generalType;
    configModel.generalContent = row.generalContent;
    configModel.remake = row.remake;
  }
};

/**
 * 添加/编辑
 */
const formSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (dialogType.value === 0) {
        addUniversalConfigApi(configModel).then((res) => {
          if (res.data.code === 2000) {
            ElMessage({
              message: "添加成功.",
              type: "success",
            });
            searchConfig(searchModel);
          } else {
            switch (res.data.code) {
              case 4001:
                ElMessage.error("key已存在，请勿重复配置.");
                break;
              default:
                ElMessage.error("添加失败.");
                break;
            }
          }
        });
      } else {
        editUniversalConfigApi(configModel).then((res) => {
          if (res.data.code === 2000) {
            ElMessage({
              message: "编辑成功.",
              type: "success",
            });
            searchConfig(searchModel);
          } else {
            switch (res.data.code) {
              case 4001:
                ElMessage.error("未找到对应的配置.");
                break;
              default:
                ElMessage.error("编辑失败.");
                break;
            }
          }
        });
      }
      Object.keys(configModel).forEach((key) => (configModel[key] = ""));
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 搜索提现订单
const search = () => {
  page.value = 1;
  if (searchModel.createDate) {
    searchModel.startTime = formatDateTime(searchModel.createDate[0]);
    searchModel.endTime = formatDateTime(searchModel.createDate[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.startTime = null;
    searchModel.endTime = null;
  }
  searchParmSearch();
  searchConfig(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

//条件查询配置列表
const searchConfig = (searchModel) => {
  findUniversalConfigApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.data;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

onMounted(() => {
  searchConfig(searchModel);
});
</script>

<style>
.select-roles {
  width: 100%;
}
</style>
